using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace GameSystems
{
    /// <summary>
    /// 异步加载系统 - 处理场景和资源的异步加载
    /// </summary>
    public class AsyncLoadingSystem : MonoBehaviour
    {
        #region Enums

        /// <summary>
        /// 加载类型
        /// </summary>
        public enum LoadType
        {
            Scene,
            AssetBundle,
            Addressable,
            Custom
        }

        /// <summary>
        /// 加载状态
        /// </summary>
        public enum LoadingStatus
        {
            Idle,
            Loading,
            Completed,
            Failed
        }

        #endregion

        #region Data Classes

        /// <summary>
        /// 加载任务
        /// </summary>
        [Serializable]
        public class LoadingTask
        {
            public string id;
            public string name;
            public LoadType type;
            public string path;
            public int priority;
            public bool isCritical;
            public float progress;
            public LoadingStatus status;
            public DateTime startTime;
            public DateTime endTime;
            public string errorMessage;
            public Dictionary<string, object> parameters;

            public LoadingTask()
            {
                id = Guid.NewGuid().ToString();
                progress = 0f;
                status = LoadingStatus.Idle;
                parameters = new Dictionary<string, object>();
            }
        }

        /// <summary>
        /// 加载队列
        /// </summary>
        [Serializable]
        public class LoadingQueue
        {
            public string name;
            public List<LoadingTask> tasks;
            public bool isSequential;
            public bool autoStart;
            public float totalProgress;
            public LoadingStatus status;

            public LoadingQueue()
            {
                name = "Default Queue";
                tasks = new List<LoadingTask>();
                isSequential = true;
                autoStart = true;
                totalProgress = 0f;
                status = LoadingStatus.Idle;
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// 加载开始事件
        /// </summary>
        [Serializable] public class LoadingStartedEvent : UnityEvent<LoadingTask> { }

        /// <summary>
        /// 加载进度更新事件
        /// </summary>
        [Serializable] public class LoadingProgressEvent : UnityEvent<LoadingTask, float> { }

        /// <summary>
        /// 加载完成事件
        /// </summary>
        [Serializable] public class LoadingCompletedEvent : UnityEvent<LoadingTask> { }

        /// <summary>
        /// 加载失败事件
        /// </summary>
        [Serializable] public class LoadingFailedEvent : UnityEvent<LoadingTask, string> { }

        /// <summary>
        /// 队列完成事件
        /// </summary>
        [Serializable] public class QueueCompletedEvent : UnityEvent<LoadingQueue> { }

        #endregion

        #region Serialized Fields

        [Header("加载配置")]
        [Tooltip("最大并发加载任务数")]
        [SerializeField] private int maxConcurrentTasks = 3;

        [Tooltip("加载超时时间（秒）")]
        [SerializeField] private float loadingTimeout = 60f;

        [Tooltip("是否启用预加载")]
        [SerializeField] private bool enablePreloading = true;

        [Tooltip("是否启用内存管理")]
        [SerializeField] private bool enableMemoryManagement = true;

        [Tooltip("内存清理阈值（MB）")]
        [SerializeField] private int memoryCleanupThreshold = 500;

        [Header("UI组件引用")]
        [Tooltip("加载进度条")]
        [SerializeField] private Slider progressBar;

        [Tooltip("加载进度文本")]
        [SerializeField] private Text progressText;

        [Tooltip("加载状态文本")]
        [SerializeField] private Text statusText;

        [Tooltip("加载提示文本")]
        [SerializeField] private Text tipText;

        [Tooltip("加载提示列表")]
        [SerializeField] private string[] loadingTips = new string[]
        {
            "正在加载游戏资源...",
            "准备游戏世界...",
            "优化游戏性能...",
            "加载精彩内容...",
            "即将完成..."
        };

        [Header("调试选项")]
        [Tooltip("是否启用调试日志")]
        [SerializeField] private bool enableDebugLogs = true;

        [Tooltip("是否显示详细进度")]
        [SerializeField] private bool showDetailedProgress = false;

        #endregion

        #region Events

        [Header("事件回调")]
        [Tooltip("加载开始时触发")]
        public LoadingStartedEvent OnLoadingStarted;

        [Tooltip("加载进度更新时触发")]
        public LoadingProgressEvent OnLoadingProgress;

        [Tooltip("加载完成时触发")]
        public LoadingCompletedEvent OnLoadingCompleted;

        [Tooltip("加载失败时触发")]
        public LoadingFailedEvent OnLoadingFailed;

        [Tooltip("队列完成时触发")]
        public QueueCompletedEvent OnQueueCompleted;

        #endregion

        #region Private Fields

        private Dictionary<string, LoadingQueue> loadingQueues = new Dictionary<string, LoadingQueue>();
        private Dictionary<string, LoadingTask> activeTasks = new Dictionary<string, LoadingTask>();
        private Queue<LoadingTask> pendingTasks = new Queue<LoadingTask>();
        private List<LoadingTask> completedTasks = new List<LoadingTask>();
        private Dictionary<string, AsyncOperation> asyncOperations = new Dictionary<string, AsyncOperation>();

        private Coroutine loadingCoroutine;
        private Coroutine memoryCheckCoroutine;
        private Coroutine tipRotationCoroutine;

        private float totalProgress = 0f;
        private int currentTipIndex = 0;

        #endregion

        #region Unity Lifecycle

        /// <summary>
        /// 初始化组件
        /// </summary>
        private void Awake()
        {
            InitializeLoadingSystem();
        }

        /// <summary>
        /// 启动时的初始化
        /// </summary>
        private void Start()
        {
            if (enableMemoryManagement)
            {
                StartMemoryCheckCoroutine();
            }

            StartTipRotationCoroutine();
        }

        /// <summary>
        /// 清理资源
        /// </summary>
        private void OnDestroy()
        {
            CleanupCoroutines();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// 创建加载队列
        /// </summary>
        /// <param name="queueName">队列名称</param>
        /// <param name="isSequential">是否顺序加载</param>
        /// <param name="autoStart">是否自动开始</param>
        /// <returns>加载队列</returns>
        public LoadingQueue CreateQueue(string queueName, bool isSequential = true, bool autoStart = true)
        {
            if (loadingQueues.ContainsKey(queueName))
            {
                LogWarning($"队列 '{queueName}' 已存在");
                return loadingQueues[queueName];
            }

            var queue = new LoadingQueue
            {
                name = queueName,
                isSequential = isSequential,
                autoStart = autoStart
            };

            loadingQueues[queueName] = queue;
            LogDebug($"创建加载队列: {queueName}");

            return queue;
        }

        /// <summary>
        /// 添加加载任务
        /// </summary>
        /// <param name="queueName">队列名称</param>
        /// <param name="taskName">任务名称</param>
        /// <param name="type">加载类型</param>
        /// <param name="path">路径</param>
        /// <param name="priority">优先级</param>
        /// <param name="isCritical">是否关键任务</param>
        /// <returns>加载任务</returns>
        public LoadingTask AddLoadingTask(string queueName, string taskName, LoadType type, string path, int priority = 0, bool isCritical = false)
        {
            if (!loadingQueues.ContainsKey(queueName))
            {
                LogError($"队列 '{queueName}' 不存在");
                return null;
            }

            var task = new LoadingTask
            {
                name = taskName,
                type = type,
                path = path,
                priority = priority,
                isCritical = isCritical
            };

            var queue = loadingQueues[queueName];
            queue.tasks.Add(task);

            // 按优先级排序
            queue.tasks.Sort((a, b) => b.priority.CompareTo(a.priority));

            LogDebug($"添加加载任务: {taskName} (队列: {queueName})");

            // 如果队列设置为自动开始且没有正在加载，开始加载
            if (queue.autoStart && queue.status == LoadingStatus.Idle)
            {
                StartLoadingQueue(queueName);
            }

            return task;
        }

        /// <summary>
        /// 开始加载队列
        /// </summary>
        /// <param name="queueName">队列名称</param>
        public void StartLoadingQueue(string queueName)
        {
            if (!loadingQueues.ContainsKey(queueName))
            {
                LogError($"队列 '{queueName}' 不存在");
                return;
            }

            var queue = loadingQueues[queueName];
            if (queue.status == LoadingStatus.Loading)
            {
                LogWarning($"队列 '{queueName}' 正在加载中");
                return;
            }

            if (queue.tasks.Count == 0)
            {
                LogWarning($"队列 '{queueName}' 没有任务");
                return;
            }

            queue.status = LoadingStatus.Loading;
            ShowLoadingUI(true);

            // 添加任务到待处理队列
            foreach (var task in queue.tasks)
            {
                if (task.status == LoadingStatus.Idle)
                {
                    pendingTasks.Enqueue(task);
                }
            }

            // 启动加载协程
            if (loadingCoroutine == null)
            {
                loadingCoroutine = StartCoroutine(LoadingCoroutine());
            }

            LogDebug($"开始加载队列: {queueName}");
        }

        /// <summary>
        /// 加载场景
        /// </summary>
        /// <param name="sceneName">场景名称</param>
        /// <param name="loadMode">加载模式</param>
        /// <param name="priority">优先级</param>
        /// <param name="isCritical">是否关键任务</param>
        /// <returns>加载任务</returns>
        public LoadingTask LoadSceneAsync(string sceneName, LoadSceneMode loadMode = LoadSceneMode.Single, int priority = 0, bool isCritical = true)
        {
            var queueName = "SceneLoading";

            if (!loadingQueues.ContainsKey(queueName))
            {
                CreateQueue(queueName, true, true);
            }

            var task = AddLoadingTask(queueName, $"LoadScene_{sceneName}", LoadType.Scene, sceneName, priority, isCritical);
            task.parameters["loadMode"] = loadMode;

            return task;
        }

        /// <summary>
        /// 加载资源
        /// </summary>
        /// <param name="resourcePath">资源路径</param>
        /// <param name="priority">优先级</param>
        /// <param name="isCritical">是否关键任务</param>
        /// <returns>加载任务</returns>
        public LoadingTask LoadResourceAsync(string resourcePath, int priority = 0, bool isCritical = false)
        {
            var queueName = "ResourceLoading";

            if (!loadingQueues.ContainsKey(queueName))
            {
                CreateQueue(queueName, false, true);
            }

            return AddLoadingTask(queueName, $"LoadResource_{resourcePath}", LoadType.Custom, resourcePath, priority, isCritical);
        }

        /// <summary>
        /// 预加载资源
        /// </summary>
        /// <param name="resources">资源路径列表</param>
        public void PreloadResources(string[] resources)
        {
            if (!enablePreloading || resources == null || resources.Length == 0)
                return;

            var queueName = "Preloading";
            var queue = CreateQueue(queueName, false, true);

            foreach (var resource in resources)
            {
                AddLoadingTask(queueName, $"Preload_{resource}", LoadType.Custom, resource, 1, false);
            }

            LogDebug($"预加载 {resources.Length} 个资源");
        }

        /// <summary>
        /// 取消加载任务
        /// </summary>
        /// <param name="taskId">任务ID</param>
        public void CancelLoadingTask(string taskId)
        {
            if (activeTasks.ContainsKey(taskId))
            {
                var task = activeTasks[taskId];
                task.status = LoadingStatus.Failed;
                task.errorMessage = "任务已取消";

                // 取消异步操作
                if (asyncOperations.ContainsKey(taskId))
                {
                    // Unity的异步操作不能直接取消，但可以标记为已取消
                    asyncOperations.Remove(taskId);
                }

                activeTasks.Remove(taskId);
                OnLoadingFailed?.Invoke(task, "任务已取消");

                LogDebug($"取消加载任务: {task.name}");
            }
        }

        /// <summary>
        /// 取消加载队列
        /// </summary>
        /// <param name="queueName">队列名称</param>
        public void CancelLoadingQueue(string queueName)
        {
            if (!loadingQueues.ContainsKey(queueName))
                return;

            var queue = loadingQueues[queueName];

            // 取消所有活动任务
            var tasksToCancel = new List<string>(activeTasks.Keys);
            foreach (var taskId in tasksToCancel)
            {
                var task = activeTasks[taskId];
                if (queue.tasks.Contains(task))
                {
                    CancelLoadingTask(taskId);
                }
            }

            // 清空待处理任务
            var tempQueue = new Queue<LoadingTask>();
            while (pendingTasks.Count > 0)
            {
                var task = pendingTasks.Dequeue();
                if (!queue.tasks.Contains(task))
                {
                    tempQueue.Enqueue(task);
                }
            }
            pendingTasks = tempQueue;

            queue.status = LoadingStatus.Failed;
            LogDebug($"取消加载队列: {queueName}");
        }

        /// <summary>
        /// 获取加载进度
        /// </summary>
        /// <param name="queueName">队列名称，为空时返回总体进度</param>
        /// <returns>加载进度</returns>
        public float GetLoadingProgress(string queueName = null)
        {
            if (string.IsNullOrEmpty(queueName))
            {
                return totalProgress;
            }

            if (!loadingQueues.ContainsKey(queueName))
                return 0f;

            var queue = loadingQueues[queueName];
            return queue.totalProgress;
        }

        /// <summary>
        /// 获取加载状态
        /// </summary>
        /// <param name="queueName">队列名称</param>
        /// <returns>加载状态</returns>
        public LoadingStatus GetLoadingStatus(string queueName = null)
        {
            if (string.IsNullOrEmpty(queueName))
            {
                if (activeTasks.Count > 0 || pendingTasks.Count > 0)
                    return LoadingStatus.Loading;
                return LoadingStatus.Completed;
            }

            if (!loadingQueues.ContainsKey(queueName))
                return LoadingStatus.Idle;

            return loadingQueues[queueName].status;
        }

        /// <summary>
        /// 清理已完成任务
        /// </summary>
        public void ClearCompletedTasks()
        {
            completedTasks.Clear();

            // 清理各队列中的已完成任务
            foreach (var queue in loadingQueues.Values)
            {
                queue.tasks.RemoveAll(task => task.status == LoadingStatus.Completed);
            }

            LogDebug("清理已完成任务");
        }

        /// <summary>
        /// 强制垃圾回收
        /// </summary>
        public void ForceGarbageCollection()
        {
            GC.Collect();
            Resources.UnloadUnusedAssets();

            LogDebug("强制执行垃圾回收");
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// 初始化加载系统
        /// </summary>
        private void InitializeLoadingSystem()
        {
            // 创建默认队列
            CreateQueue("Default", true, true);
            CreateQueue("SceneLoading", true, true);
            CreateQueue("ResourceLoading", false, true);
            CreateQueue("Preloading", false, true);

            ShowLoadingUI(false);
        }

        /// <summary>
        /// 加载协程
        /// </summary>
        private IEnumerator LoadingCoroutine()
        {
            LogDebug("开始加载协程");

            while (pendingTasks.Count > 0 || activeTasks.Count > 0)
            {
                // 处理新任务
                while (pendingTasks.Count > 0 && activeTasks.Count < maxConcurrentTasks)
                {
                    var task = pendingTasks.Dequeue();
                    StartLoadingTask(task);
                }

                // 更新进度
                UpdateTotalProgress();

                yield return null;
            }

            // 所有任务完成
            loadingCoroutine = null;
            totalProgress = 1f;
            UpdateProgressUI();

            // 检查队列状态
            CheckQueueCompletion();

            LogDebug("加载协程完成");
        }

        /// <summary>
        /// 开始加载任务
        /// </summary>
        private void StartLoadingTask(LoadingTask task)
        {
            task.status = LoadingStatus.Loading;
            task.startTime = DateTime.Now;

            activeTasks[task.id] = task;
            OnLoadingStarted?.Invoke(task);

            LogDebug($"开始加载任务: {task.name}");

            switch (task.type)
            {
                case LoadType.Scene:
                    StartCoroutine(LoadSceneCoroutine(task));
                    break;
                case LoadType.AssetBundle:
                    StartCoroutine(LoadAssetBundleCoroutine(task));
                    break;
                case LoadType.Addressable:
                    StartCoroutine(LoadAddressableCoroutine(task));
                    break;
                case LoadType.Custom:
                    StartCoroutine(LoadCustomCoroutine(task));
                    break;
            }
        }

        /// <summary>
        /// 加载场景协程
        /// </summary>
        private IEnumerator LoadSceneCoroutine(LoadingTask task)
        {
            var sceneName = task.path;
            var loadMode = task.parameters.ContainsKey("loadMode") ?
                (LoadSceneMode)task.parameters["loadMode"] : LoadSceneMode.Single;

            AsyncOperation asyncOperation = null;

            try
            {
                asyncOperation = SceneManager.LoadSceneAsync(sceneName, loadMode);
                asyncOperations[task.id] = asyncOperation;

                if (asyncOperation != null)
                {
                    while (!asyncOperation.isDone)
                    {
                        task.progress = asyncOperation.progress;
                        OnLoadingProgress?.Invoke(task, task.progress);
                        yield return null;
                    }

                    task.progress = 1f;
                    task.status = LoadingStatus.Completed;
                    task.endTime = DateTime.Now;
                }
                else
                {
                    throw new Exception("场景加载失败");
                }
            }
            catch (Exception e)
            {
                task.status = LoadingStatus.Failed;
                task.errorMessage = e.Message;
                task.endTime = DateTime.Now;
                OnLoadingFailed?.Invoke(task, e.Message);
            }
            finally
            {
                FinishLoadingTask(task);
                asyncOperations.Remove(task.id);
            }
        }

        /// <summary>
        /// 加载资源包协程
        /// </summary>
        private IEnumerator LoadAssetBundleCoroutine(LoadingTask task)
        {
            // 实际项目中，这里应该实现AssetBundle加载逻辑
            yield return new WaitForSeconds(1f);

            // 模拟加载成功
            task.progress = 1f;
            task.status = LoadingStatus.Completed;
            task.endTime = DateTime.Now;

            FinishLoadingTask(task);
        }

        /// <summary>
        /// 加载Addressable资源协程
        /// </summary>
        private IEnumerator LoadAddressableCoroutine(LoadingTask task)
        {
            // 实际项目中，这里应该实现Addressable加载逻辑
            yield return new WaitForSeconds(1f);

            // 模拟加载成功
            task.progress = 1f;
            task.status = LoadingStatus.Completed;
            task.endTime = DateTime.Now;

            FinishLoadingTask(task);
        }

        /// <summary>
        /// 加载自定义资源协程
        /// </summary>
        private IEnumerator LoadCustomCoroutine(LoadingTask task)
        {
            // 模拟加载过程
            float loadTime = UnityEngine.Random.Range(0.5f, 2f);
            float elapsedTime = 0f;

            while (elapsedTime < loadTime)
            {
                elapsedTime += Time.deltaTime;
                task.progress = elapsedTime / loadTime;
                OnLoadingProgress?.Invoke(task, task.progress);
                yield return null;
            }

            task.progress = 1f;
            task.status = LoadingStatus.Completed;
            task.endTime = DateTime.Now;

            // 实际的资源加载逻辑
            try
            {
                var resource = Resources.LoadAsync(task.path);
                yield return resource;

                if (resource.asset == null)
                {
                    throw new Exception($"资源 '{task.path}' 不存在");
                }
            }
            catch (Exception e)
            {
                task.status = LoadingStatus.Failed;
                task.errorMessage = e.Message;
                OnLoadingFailed?.Invoke(task, e.Message);
            }

            FinishLoadingTask(task);
        }

        /// <summary>
        /// 完成加载任务
        /// </summary>
        private void FinishLoadingTask(LoadingTask task)
        {
            if (activeTasks.ContainsKey(task.id))
            {
                activeTasks.Remove(task.id);
            }

            completedTasks.Add(task);

            if (task.status == LoadingStatus.Completed)
            {
                OnLoadingCompleted?.Invoke(task);
                LogDebug($"任务完成: {task.name} (耗时: {(task.endTime - task.startTime).TotalSeconds:F2}秒)");
            }
        }

        /// <summary>
        /// 更新总进度
        /// </summary>
        private void UpdateTotalProgress()
        {
            if (loadingQueues.Count == 0)
            {
                totalProgress = 0f;
                return;
            }

            float totalTasks = 0f;
            float completedTasks = 0f;

            foreach (var queue in loadingQueues.Values)
            {
                if (queue.tasks.Count == 0) continue;

                totalTasks += queue.tasks.Count;

                foreach (var task in queue.tasks)
                {
                    if (task.status == LoadingStatus.Completed)
                    {
                        completedTasks += 1f;
                    }
                    else if (task.status == LoadingStatus.Loading)
                    {
                        completedTasks += task.progress;
                    }
                }

                // 更新队列进度
                queue.totalProgress = completedTasks / totalTasks;
            }

            totalProgress = completedTasks / totalTasks;
            UpdateProgressUI();
        }

        /// <summary>
        /// 更新进度UI
        /// </summary>
        private void UpdateProgressUI()
        {
            // 更新进度条
            if (progressBar != null)
            {
                progressBar.value = totalProgress;
            }

            // 更新进度文本
            if (progressText != null)
            {
                if (showDetailedProgress)
                {
                    progressText.text = $"加载进度: {totalProgress:P0} ({completedTasks.Count}/{completedTasks.Count + activeTasks.Count + pendingTasks.Count})";
                }
                else
                {
                    progressText.text = $"加载进度: {totalProgress:P0}";
                }
            }

            // 更新状态文本
            if (statusText != null && activeTasks.Count > 0)
            {
                var firstTask = GetFirstActiveTask();
                if (firstTask != null)
                {
                    statusText.text = $"正在加载: {firstTask.name}";
                }
            }
        }

        /// <summary>
        /// 获取第一个活动任务
        /// </summary>
        private LoadingTask GetFirstActiveTask()
        {
            foreach (var task in activeTasks.Values)
            {
                return task;
            }
            return null;
        }

        /// <summary>
        /// 检查队列完成
        /// </summary>
        private void CheckQueueCompletion()
        {
            foreach (var queue in loadingQueues.Values)
            {
                if (queue.status == LoadingStatus.Loading)
                {
                    bool allCompleted = true;
                    foreach (var task in queue.tasks)
                    {
                        if (task.status != LoadingStatus.Completed && task.status != LoadingStatus.Failed)
                        {
                            allCompleted = false;
                            break;
                        }
                    }

                    if (allCompleted)
                    {
                        queue.status = LoadingStatus.Completed;
                        OnQueueCompleted?.Invoke(queue);
                        LogDebug($"队列完成: {queue.name}");
                    }
                }
            }

            // 如果所有队列都完成，隐藏加载UI
            bool allQueuesCompleted = true;
            foreach (var queue in loadingQueues.Values)
            {
                if (queue.status == LoadingStatus.Loading)
                {
                    allQueuesCompleted = false;
                    break;
                }
            }

            if (allQueuesCompleted)
            {
                ShowLoadingUI(false);
            }
        }

        /// <summary>
        /// 显示/隐藏加载UI
        /// </summary>
        private void ShowLoadingUI(bool show)
        {
            if (progressBar != null)
                progressBar.gameObject.SetActive(show);

            if (progressText != null)
                progressText.gameObject.SetActive(show);

            if (statusText != null)
                statusText.gameObject.SetActive(show);

            if (tipText != null)
                tipText.gameObject.SetActive(show);
        }

        /// <summary>
        /// 启动内存检查协程
        /// </summary>
        private void StartMemoryCheckCoroutine()
        {
            if (memoryCheckCoroutine != null)
            {
                StopCoroutine(memoryCheckCoroutine);
            }

            memoryCheckCoroutine = StartCoroutine(MemoryCheckCoroutine());
        }

        /// <summary>
        /// 内存检查协程
        /// </summary>
        private IEnumerator MemoryCheckCoroutine()
        {
            while (true)
            {
                yield return new WaitForSeconds(5f);

                long memoryUsage = GC.GetTotalMemory(false);
                float memoryUsageMB = memoryUsage / (1024f * 1024f);

                if (memoryUsageMB > memoryCleanupThreshold)
                {
                    LogDebug($"内存使用超过阈值 ({memoryUsageMB:F2}MB)，执行清理");
                    ForceGarbageCollection();
                }
            }
        }

        /// <summary>
        /// 启动提示轮换协程
        /// </summary>
        private void StartTipRotationCoroutine()
        {
            if (tipRotationCoroutine != null)
            {
                StopCoroutine(tipRotationCoroutine);
            }

            tipRotationCoroutine = StartCoroutine(TipRotationCoroutine());
        }

        /// <summary>
        /// 提示轮换协程
        /// </summary>
        private IEnumerator TipRotationCoroutine()
        {
            while (true)
            {
                yield return new WaitForSeconds(3f);

                if (tipText != null && loadingTips.Length > 0)
                {
                    currentTipIndex = (currentTipIndex + 1) % loadingTips.Length;
                    tipText.text = loadingTips[currentTipIndex];
                }
            }
        }

        /// <summary>
        /// 清理协程
        /// </summary>
        private void CleanupCoroutines()
        {
            if (loadingCoroutine != null)
            {
                StopCoroutine(loadingCoroutine);
                loadingCoroutine = null;
            }

            if (memoryCheckCoroutine != null)
            {
                StopCoroutine(memoryCheckCoroutine);
                memoryCheckCoroutine = null;
            }

            if (tipRotationCoroutine != null)
            {
                StopCoroutine(tipRotationCoroutine);
                tipRotationCoroutine = null;
            }
        }

        #endregion

        #region Debug Methods

        /// <summary>
        /// 调试日志
        /// </summary>
        private void LogDebug(string message)
        {
            if (enableDebugLogs)
                Debug.Log($"[AsyncLoadingSystem] {message}");
        }

        /// <summary>
        /// 警告日志
        /// </summary>
        private void LogWarning(string message)
        {
            if (enableDebugLogs)
                Debug.LogWarning($"[AsyncLoadingSystem] {message}");
        }

        /// <summary>
        /// 错误日志
        /// </summary>
        private void LogError(string message)
        {
            if (enableDebugLogs)
                Debug.LogError($"[AsyncLoadingSystem] {message}");
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// 总加载进度
        /// </summary>
        public float TotalProgress => totalProgress;

        /// <summary>
        /// 活动任务数量
        /// </summary>
        public int ActiveTaskCount => activeTasks.Count;

        /// <summary>
        /// 待处理任务数量
        /// </summary>
        public int PendingTaskCount => pendingTasks.Count;

        /// <summary>
        /// 已完成任务数量
        /// </summary>
        public int CompletedTaskCount => completedTasks.Count;

        /// <summary>
        /// 最大并发任务数
        /// </summary>
        public int MaxConcurrentTasks
        {
            get => maxConcurrentTasks;
            set => maxConcurrentTasks = Mathf.Max(1, value);
        }

        /// <summary>
        /// 是否启用内存管理
        /// </summary>
        public bool EnableMemoryManagement
        {
            get => enableMemoryManagement;
            set => enableMemoryManagement = value;
        }

        /// <summary>
        /// 内存清理阈值
        /// </summary>
        public int MemoryCleanupThreshold
        {
            get => memoryCleanupThreshold;
            set => memoryCleanupThreshold = Mathf.Max(100, value);
        }

        #endregion
    }
}
